package com.gulimall.product.exception;

import com.gulimall.common.enums.ExceptionEnum;
import com.gulimall.common.exception.BaseRunException;
import com.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常处理器
 *
 * @author ht
 */
@RestControllerAdvice
@Slf4j
public class BaseRunExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BaseRunException.class)
    public R handleBaseRunException(BaseRunException e) {
        R r = new R();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(500, "请求出现异常，请联系管理员处理！");
    }

    @ExceptionHandler(RuntimeException.class)
    public R handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return R.error(500, e.getMessage());
    }

    /**
     * 校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        List<String> errorList = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                log.error("数据校验异常 : 对象{" + fieldError.getObjectName() + "},字段{" + fieldError.getField() +
                        "},异常信息{" + fieldError.getDefaultMessage() + "}");
                errorList.add(p.getDefaultMessage());
            });
        }
        return R.error(ExceptionEnum.INVALID_PARAM_ERROR.getStatus(), ExceptionEnum.INVALID_PARAM_ERROR.getMessage(), errorList);
    }
}
